package org.xnat.xnatfs.asset;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;

public abstract class HttpResponseAsset implements IAsset {
  private HttpResponse response;

  public HttpResponseAsset ( HttpResponse response ) {
    this.response = response;
  }

  @Override
  public boolean authorised () {
    return getStatusCode () != HttpStatus.SC_UNAUTHORIZED && getStatusCode () != HttpStatus.SC_FORBIDDEN;
  }

  @Override
  public void close () throws IOException {
    if ( getEntity () != null ) {
      getEntity ().consumeContent ();
    }
  }

  @Override
  protected void finalize () throws Throwable {
    super.finalize ();
    try {
      // make sure that the entity is consumed
      close ();
    } catch ( Throwable e ) {
      // ignore
    }
  }

  @Override
  public boolean found () {
    return true;
    // return getStatusCode () != HttpStatus.SC_NOT_FOUND;
  }

  @Override
  public long getContentLength () {
    if ( getEntity () != null ) {
      return getEntity ().getContentLength ();
    }
    return -1L;
  }

  protected HttpEntity getEntity () {
    return response.getEntity ();
  }

  protected HttpResponse getResponse () {
    return response;
  }

  private int getStatusCode () {
    return response.getStatusLine ().getStatusCode ();
  }
}
